<template>
  <div class="app-container flex">
    <!-- <el-alert class="warn-content" title="温馨提示" type="success" show-icon :closable="false">
      <p>运费模板不会自动与商品关联，您可以在发布或者修改商品信息时选择运费模板</p>
    </el-alert>
    <br /> -->

    <el-tabs v-model="activeName" tab-position="left" class="flex f-s-0 f-c" @tab-click="handleClickTab">
      <!-- <el-tab-pane label="快速录入" name="kuaisu"></el-tab-pane> -->
      <el-tab-pane label="基础信息" name="jichu"></el-tab-pane>
      <!-- <el-tab-pane label="秒杀拼团" name="miaosha"></el-tab-pane> -->
      <el-tab-pane label="商品规格" name="xiaoshou"></el-tab-pane>
      <el-tab-pane label="图文描述" name="tuwen"></el-tab-pane>
      <el-tab-pane label="支付信息" name="zhifu"></el-tab-pane>
      <el-tab-pane label="物流信息" name="wuliu"></el-tab-pane>
      <el-tab-pane label="售后信息" name="shouhou"></el-tab-pane>
    </el-tabs>
    <div id="wrap-form" style="height:84vh;overflow-y: scroll;" class="flex flex-1 f-c">
    <el-form class="flex flex-1 f-c" ref="postForm" :model="postForm"  label-position="right" style="width: 90%;"
       label-width="120px">
      <!-- <el-card id="kuaisu" class="box-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>快速录入</span>
        </div>
        <el-form-item label="总商品库" prop="thirdGoodsUrl">
          <el-button-group>
            <el-button size="mini" type="primary"  @click="openGoodsDialog">选择商品</el-button>
          </el-button-group>
        </el-form-item>
        <el-form-item label="商品链接" prop="thirdGoodsUrl">
          <el-input v-model="thirdGoodsUrl" style="width: 60%;" placeholder="淘宝,京东,拼多多等电商平台商品链接" />
          <el-button @click="getThirdDetail()" size="mini" type="primary" :loading="autoGetLoading">自动识别</el-button>
        </el-form-item>
        <el-form-item label="温馨提醒" prop="thirdGoodsUrl">
          <p class="tips" style="color: #468847;">*目前仅支持识别淘宝，京东，拼多多商品详情，其他电商平台后续会升级更新</p>
        </el-form-item>
        <el-form-item label="测试链接" prop="thirdGoodsUrl">
          <p class="tips" style="color: #468847;">https://mobile.yangkeduo.com/goods.html?goods_id=373696623577
        </p>
        </el-form-item>

        <goodsDialog
         v-if="showGoods"
          ref="goodsDialog"
          @selected="selectedGoods"
          @close="closeGoodsDialog"
        ></goodsDialog>
        </el-card> -->
      <br>
      <el-card id="jichu" class="box-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>基础信息</span>
        </div>


       <el-form-item prop="title" label="请输入宝贝标题" :rules="[{ required: true, message: '请输入宝贝标题', trigger: 'blur' }]">
          <el-input type="text" v-model="postForm.title" placeholder="" style="width: 60%;" />
        </el-form-item>
<!--      <el-form-item style="margin-bottom: 40px;" prop="title" :rules="[{ required: true, message: '请输入宝贝标题', trigger: 'blur' }]" label="请输入宝贝标题">
          <MDinput v-model="postForm.title" :maxlength="100" name="title" required>请输入宝贝标题</MDinput>
        </el-form-item> -->
        <el-form-item prop="goodsCateId" label="商品类目" :rules="[{ required: true, message: '请选择', trigger: 'change' }]">
          <el-cascader
              :props="props"
              style="width: 60%;"
              v-model="postForm.goodsCateId"
              placeholder="试试搜索"
              :options="goodsCateOptions"
              filterable></el-cascader>
        </el-form-item>
       <el-form-item prop="shopCateId" label="店铺类目" :rules="[{ required: true, message: '请选择', trigger: 'change' }]">
          <el-cascader
              :props="props"
              style="width: 60%;"
              v-model="postForm.shopCateId"
              placeholder="试试搜索"
              :options="shopCateOptions"
              filterable></el-cascader>
          <el-button @click="$router.push('/cate/cateList')"size="mini" type="danger">新建分类</el-button>
          <el-button @click="getShopCateList"size="mini" type="danger">刷新</el-button>
        </el-form-item>
      </el-card>
      <!-- <br>
      <el-card id="miaosha" class="box-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>秒杀拼团</span>
        </div>
        <el-form-item label="商品类型" prop="type" :rules="[{ required: true, message: '请选择', trigger: 'change' }]">
            <el-radio-group v-model="postForm.type" size="small" :disabled="postForm.id != null">
              <el-radio :label="1" border>普通商品</el-radio>
              <el-radio :label="2" border>秒杀商品</el-radio>
              <el-radio :label="3" border>拼团商品</el-radio>
            </el-radio-group>
        </el-form-item>
        <div v-if="postForm.type == 2 ">
          <el-form-item  prop="seckillDateRange" label="秒杀时间" :rules="[{ required: true, message: '请选择', trigger: 'blur' }]" >
            <el-date-picker
              style="width: 60%;"
              v-model="postForm.seckillDateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="秒杀限购" prop="seckillLimitNum" :rules="[{ required: true, message: '必填', trigger: 'blur' }]">
            <el-input v-model.number="postForm.seckillLimitNum"style="width: 60%;" placeholder="请输入秒杀限购数量" />
          </el-form-item>
          </div>
          <div v-if="postForm.type == 3 ">
            <el-form-item label="拼团类型" prop="groupType" :rules="[{ required: true, message: '请选择', trigger: 'change' }]">
                <el-radio-group v-model="postForm.groupType" size="small">
                  <el-radio :label="1" border>普通拼团</el-radio>
                  <el-radio :label="2" border>阶梯拼团</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item v-if="postForm.groupType == 2" label="* 阶梯配置" prop="groupConfig" >
                <span style="font-size: 13px;font-weight: 550;color: #18bc9c;">成团人数</span>
                <span style="font-size: 13px;font-weight: 550;margin-left: 100px; color: #18bc9c;">优惠阶梯%</span>
                <div v-for="(item,index)  in groupList" style="margin-top: 3px;margin-left: 70px;">
                    <el-input v-model.number="item.num" placeholder="请输入成团人数" style="width: 150px;"></el-input>
                    <el-input v-model="item.discounts" placeholder="请输入优惠阶梯" style="width: 150px;"></el-input>
                    <el-button v-if="index != 0" type="danger"  size="mini"  @click="deleteGroup(index)" icon="el-icon-delete"></el-button>
                </div>

                <el-form-item style="margin-left: 70px;">
                  <el-button-group>
                    <el-button type="success"  size="mini"  @click="addGroup" >追加</el-button>
                  </el-button-group>
                </el-form-item>

            </el-form-item>
            <el-form-item v-if="postForm.groupType == 1" label="成团人数" prop="groupNum" :rules="[{ required: true, message: '必填', trigger: 'blur' }]">
              <el-input v-model.number="postForm.groupNum"style="width: 60%;" placeholder="请输入组团成团人数" />
            </el-form-item>
            <el-form-item label="组团限时" prop="groupLimitHours" :rules="[{ required: true, message: '必填', trigger: 'blur' }]">
              <el-input v-model.number="postForm.groupLimitHours"style="width: 60%;" placeholder="请输入组团限时(小时)" />
              <span class="tips">单位:小时</span>
            </el-form-item>
            <el-form-item label="个人限购" prop="groupLimitBuy" :rules="[{ required: true, message: '必填', trigger: 'blur' }]">
              <el-input v-model.number="postForm.groupLimitBuy"style="width: 60%;" placeholder="请输入个人购买限制" />
              <span class="tips">单位:次数</span>
            </el-form-item>
            <el-form-item label="是否单买" prop="groupSingleBuy" :rules="[{ required: true, message: '请选择', trigger: 'change' }]">
                <el-radio-group v-model="postForm.groupSingleBuy" size="small">
                  <el-radio :label="1" border>开启单购</el-radio>
                  <el-radio :label="2" border>关闭单购</el-radio>
                </el-radio-group>
            </el-form-item>
        </div>
      </el-card> -->
      <br>
      <el-card id="xiaoshou" class="box-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>商品规格</span>
        </div>

                              <el-form-item label="商品规格：" props="specType">
                                <el-radio-group
                                  v-model="formValidate.specType"
                                  @change="onChangeSpecnew(formValidate.specType)"
                                  :disabled="isDisabled"
                                >
                                  <el-radio :label="false" class="radio"  @click="defaultAttr">单规格</el-radio>
                                  <el-radio :label="true" @click="manyAttr" >多规格</el-radio>
                                </el-radio-group>







<!--          <el-button type="default" class="button-new-tag" size="mini" @click="defaultAttr" icon="el-icon">统一规格</el-button>-->
<!--          <el-button type="default" class="button-new-tag" size="mini" @click="manyAttr" icon="el-icon">多规格</el-button>-->

          <br><br>
          <div v-if="formValidate.specType">
            <el-input v-model="attrKey" placeholder="多个产品属性以空格隔开" style="width: 300px;" />
            <el-button type="warning" class="button-new-tag" size="mini" @click="addAttrKey" icon="el-icon-circle-plus">新增属性</el-button>
          </div>


          <div class="b-color-d margin-t12" style="width: 100%;"  v-for="(item, index) in attrKeyList">
            <div class="flex f-a-c f-j-s  h-40 bg-color-5 padding-lr12"  v-if="formValidate.specType">
              <p class="flex f-a-c" style="font-weight: bold;">{{item.attrKey}}</p>
              <i class="el-icon el-icon-error" @click="handleCloseKey(index)"></i>
            </div>
            <div class="flex padding-12"  v-if="formValidate.specType">
              <div class="flex f-a-s f-s-0 margin-r20" >
                <div class="flex">
                  <el-input v-model="item.attrValue" placeholder="多规格以空格隔开" class="w-200">
                  </el-input>
                  &nbsp;
                  <el-button type="info" size="mini" @click="addAttrValue(item)" icon="el-icon-plus"></el-button>
                </div>

              </div>
              <div class="flex f-w">
                <el-tag
                size="large"
                class="margin-t2 margin-r10"
                  :key="child"
                  v-for="(itemValue, child) in item.attrValueList"
                  closable
                  :disable-transitions="false"
                  @close="handleCloseValue(item, itemValue,index)">
                  {{itemValue}}
                </el-tag>
              </div>
            </div>
          </div>

          			<el-table
                  v-if="attrKeyList && attrKeyList.length > 0"
          			  :data="skuList"
          			  border
                  :header-cell-style="{background:'#d9edf7',color:'#3498db', font:'18px'}"
          			  style="width: 100%;mmargin-top: 10px;"
          			>
          			  <el-table-column v-for="(attr, index) in attrKeyList" :key="attr.keyId" :label="attr.attrKey">
          					<template slot-scope="scope">
          						{{ scope.row[index] }}
          			    </template>
          			  </el-table-column>
          				<el-table-column label="原价"  width="80" align="center">
          				  <template slot-scope="scope">
          				    <el-input class="edit-input" size="mini" v-model="scope.row[attrLength]"/>
          				  </template>
          				</el-table-column>
                  <el-table-column label="现价"  width="80" align="center">
                    <template slot-scope="scope">
                      <el-input class="edit-input" size="mini" v-model="scope.row[attrLength+1]"/>
                    </template>
                  </el-table-column>
                  <el-table-column label="库存" width="80"  align="center">
                    <template slot-scope="scope">
                      <el-input class="edit-input" size="mini" v-model.number="scope.row[attrLength+2]"/>
                    </template>
                  </el-table-column>
          				<el-table-column label="重量(kg)" width="80"  align="center">
          				  <template slot-scope="scope">
          				    <el-input  class="edit-input" size="mini" v-model="scope.row[attrLength+3]"/>
          				  </template>
          				</el-table-column>
          				<el-table-column label="编码" width="80"  align="center">
          				  <template slot-scope="scope">
          				    <el-input class="edit-input" size="mini" v-model="scope.row[attrLength+4]"/>
          				  </template>
          				</el-table-column>
          				<el-table-column label="图片" width="80" align="center">
          				  <template slot-scope="scope">
                      <SingleUpload class="flex f-a-c f-j-c" style="height:50px;width:50px;" v-model="scope.row[attrLength+5]"/>
          				  </template>
          				</el-table-column>
          			</el-table>

                <div v-if="attrKeyList && attrKeyList.length > 0" style="margin-left: 65px;font-size: 13px;">
                  <a v-if="!batchSet" class="link-type" @click="batchSet = true">是否批量设置?</a>
                  <a v-else class="link-type" @click="batchSet = false">取消批量设置?</a>
                  <br>
                    <div v-if="batchSet">
                      <el-input placeholder="批量设置原价" v-model="temp.oriPrice" style="width: 30%;">
                          <template slot="prepend">原价</template>
                         <el-button slot="append" @click="batchSetParams(temp.oriPrice, attrLength)">批量设置</el-button>
                      </el-input>
                      <br>
                      <el-input placeholder="批量设置现价" v-model="temp.price" style="width: 30%;margin-top: 10px;">
                          <template slot="prepend">现价</template>
                         <el-button slot="append" @click="batchSetParams(temp.price, attrLength+1)">批量设置</el-button>
                      </el-input>
                      <br>
                      <el-input placeholder="批量设置库存" v-model="temp.stock" style="width: 30%;margin-top: 10px;">
                          <template slot="prepend">库存</template>
                         <el-button slot="append" @click="batchSetParams(temp.stock, attrLength+2)">批量设置</el-button>
                      </el-input>
                      <br>
                      <el-input placeholder="批量设置重量" v-model="temp.weight" style="width: 30%;margin-top: 10px;">
                          <template slot="prepend">重量</template>
                         <el-button slot="append" @click="batchSetParams(temp.weight, attrLength+3)">批量设置</el-button>
                      </el-input>
                      <br>
                      <el-input placeholder="批量设置编码" v-model="temp.skuNo" style="width: 30%;margin-top: 10px;">
                          <template slot="prepend">编码</template>
                         <el-button slot="append" @click="batchSetParams(temp.skuNo, attrLength+4)">批量设置</el-button>
                      </el-input>
                    </div>
                </div>

        </el-form-item>















<!-- <el-col :span="24">-->
<!--                      <el-form-item label="商品规格：" props="specType">-->
<!--                        <el-radio-group-->
<!--                          v-model="formValidate.specType"-->
<!--                          @change="onChangeSpec(formValidate.specType)"-->
<!--                          :disabled="isDisabled"-->
<!--                        >-->
<!--                          <el-radio :label="false" class="radio">单规格</el-radio>-->
<!--                          <el-radio :label="true">多规格</el-radio>-->
<!--                        </el-radio-group>-->
<!--                      </el-form-item>-->
<!--                    &lt;!&ndash;  <el-form-item label="佣金设置：" props="isSub">-->
<!--                        <el-radio-group-->
<!--                          v-model="formValidate.isSub"-->
<!--                          @change="onChangetype(formValidate.isSub)"-->
<!--                          :disabled="isDisabled"-->
<!--                        >-->
<!--                          <el-radio :label="true" class="radio">单独设置</el-radio>-->
<!--                          <el-radio :label="false">默认设置</el-radio>-->
<!--                        </el-radio-group>-->
<!--                      </el-form-item> &ndash;&gt;-->
<!--                    </el-col>-->
<!--                    <el-col v-if="formValidate.specType && !isDisabled" :span="24" class="noForm">-->
<!--                      <el-form-item label="选择规格：" prop="">-->
<!--                        <div class="acea-row">-->
<!--                          <el-select v-model="formValidate.selectRule">-->
<!--                            <el-option v-for="item in ruleList" :key="item.id" :label="item.ruleName" :value="item.id" />-->
<!--                          </el-select>-->
<!--                          <el-button type="primary" class="mr20" @click="confirm">确认</el-button>-->
<!--                          <el-button class="mr15" @click="addRule">添加规格</el-button>-->
<!--                        </div>-->
<!--                      </el-form-item>-->
<!--                      <el-form-item>-->
<!--                        <div v-for="(item, index) in formValidate.attr" :key="index">-->
<!--                          <div class="acea-row row-middle">-->
<!--                            <span class="mr5">{{ item.attrName }}</span-->
<!--                            ><i class="el-icon-circle-close" @click="handleRemoveAttr(index)" />-->
<!--                          </div>-->
<!--                          <div class="rulesBox">-->
<!--                            <el-tag-->
<!--                              v-for="(j, indexn) in item.attrValue"-->
<!--                              :key="indexn"-->
<!--                              closable-->
<!--                              size="medium"-->
<!--                              :disable-transitions="false"-->
<!--                              class="mb5 mr10"-->
<!--                              @close="handleClose(item.attrValue, indexn)"-->
<!--                            >-->
<!--                              {{ j }}-->
<!--                            </el-tag>-->
<!--                            <el-input-->
<!--                              v-if="item.inputVisible"-->
<!--                              ref="saveTagInput"-->
<!--                              v-model.trim="item.attrValue.attrsVal"-->
<!--                              class="input-new-tag"-->
<!--                              size="small"-->
<!--                              @keyup.enter.native="createAttr(item.attrValue.attrsVal, index)"-->
<!--                              @blur="createAttr(item.attrValue.attrsVal, index)"-->
<!--                            />-->
<!--                            <el-button v-else class="button-new-tag" size="small" @click="showInput(item)">+ 添加</el-button>-->
<!--                          </div>-->
<!--                        </div>-->
<!--                      </el-form-item>-->
<!--                      <el-row>-->
<!--                        <el-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">-->
<!--                          <el-form-item label="规格：">-->
<!--                            <el-input v-model.trim="formDynamic.attrsName" placeholder="请输入规格" />-->
<!--                          </el-form-item>-->
<!--                        </el-col>-->
<!--                        <el-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">-->
<!--                          <el-form-item label="规格值：">-->
<!--                            <el-input v-model.trim="formDynamic.attrsVal" placeholder="请输入规格值" />-->
<!--                          </el-form-item>-->
<!--                        </el-col>-->
<!--                        <el-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">-->
<!--                          <el-form-item>-->
<!--                            <el-button type="primary" @click="createAttrName">确定</el-button>-->
<!--                            <el-button @click="offAttrName">取消</el-button>-->
<!--                          </el-form-item>-->
<!--                        </el-col>-->
<!--                      </el-row>-->
<!--                      <el-form-item v-if="!isBtn">-->
<!--                        <el-button type="primary" icon="md-add" class="mr15" @click="addBtn">添加新规格</el-button>-->
<!--                      </el-form-item>-->
<!--</el-col>-->













<!--          <el-col v-if="formValidate.attr.length > 0 && formValidate.specType && !isDisabled" :span="24" class="noForm">-->
<!--            <el-form-item label="批量设置：">-->
<!--              <el-table :data="oneFormBatch" border class="tabNumWidth" size="mini">-->
<!--                <el-table-column align="center" label="图片" min-width="80">-->
<!--                  <template slot-scope="scope">-->
<!--                    <div class="upLoadPicBox" @click="modalPicTap('1', 'pi')">-->
<!--                      <div v-if="scope.row.image" class="pictrue tabPic"><img :src="scope.row.image" /></div>-->
<!--                      <div v-else class="upLoad tabPic">-->
<!--                        <i class="el-icon-camera cameraIconfont" />-->
<!--                      </div>-->
<!--                    </div>-->
<!--                  </template>-->
<!--                </el-table-column>-->
<!--                <el-table-column align="center" label="一级返佣(%)" min-width="120">-->
<!--                  <template slot-scope="scope">-->
<!--                    <el-input-->
<!--                      maxlength="6"-->
<!--                      v-model.trim="scope.row.brokerage"-->
<!--                      type="number"-->
<!--                      :min="0"-->
<!--                      :max="scope.row.price"-->
<!--                      class="priceBox"-->
<!--                      @keyup.native="keyupEventBrokerage('brokerage', scope.$index, 1)"-->
<!--                    />-->
<!--                  </template>-->
<!--                </el-table-column>-->
<!--                <el-table-column align="center" label="二级返佣(%)" min-width="120">-->
<!--                  <template slot-scope="scope">-->
<!--                    <el-input-->
<!--                      maxlength="6"-->
<!--                      v-model.trim="scope.row.brokerageTwo"-->
<!--                      type="number"-->
<!--                      :min="0"-->
<!--                      :max="scope.row.price"-->
<!--                      class="priceBox"-->
<!--                      @keyup.native="keyupEventBrokerage('brokerageTwo', scope.$index, 1)"-->
<!--                    />-->
<!--                  </template>-->
<!--                </el-table-column>-->
<!--                <el-table-column-->
<!--                  v-for="(item, iii) in attrValue"-->
<!--                  :key="iii"-->
<!--                  :label="formThead[iii].title"-->
<!--                  align="center"-->
<!--                  min-width="120"-->
<!--                  :type="formThead[iii].title === '商品编号' ? 'text' : 'number'"-->
<!--                  :min="0"-->
<!--                >-->
<!--                  <template slot-scope="scope">-->
<!--                    <el-input-->
<!--                      maxlength="6"-->
<!--                      v-model.trim="scope.row[iii]"-->
<!--                      type="number"-->
<!--                      :min="0"-->
<!--                      class="priceBox"-->
<!--                      @keyup.native="keyupEvent(iii, scope.row[iii], scope.$index, 1)"-->
<!--                    />-->
<!--                  </template>-->
<!--                </el-table-column>-->
<!--                <template v-if="formValidate.isSub"> </template>-->
<!--                <el-table-column align="center" label="操作" min-width="80">-->
<!--                  <template>-->
<!--                    <el-button type="text" class="submission" @click="batchAdd">批量添加</el-button>-->
<!--                  </template>-->
<!--                </el-table-column>-->
<!--              </el-table>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">-->
<!--            <el-form-item v-if="formValidate.specType === false">-->
<!--              <el-table :data="OneattrValue" border class="tabNumWidth" size="mini">-->
<!--                <el-table-column align="center" label="图片" min-width="80">-->
<!--                  <template slot-scope="scope">-->
<!--                    <div class="upLoadPicBox" @click="modalPicTap('1', 'dan', 'pi')">-->
<!--                      <div v-if="formValidate.image" class="pictrue tabPic"><img :src="scope.row.image" /></div>-->
<!--                      <div v-else class="upLoad tabPic">-->
<!--                        <i class="el-icon-camera cameraIconfont" />-->
<!--                      </div>-->
<!--                    </div>-->
<!--                  </template>-->
<!--                </el-table-column>-->
<!--                <template v-if="formValidate.isSub">-->
<!--                  <el-table-column align="center" label="一级返佣(%)" min-width="120">-->
<!--                    <template slot-scope="scope">-->
<!--                      <el-input-->
<!--                        maxlength="6"-->
<!--                        :disabled="isDisabled"-->
<!--                        v-model.trim="scope.row.brokerage"-->
<!--                        type="number"-->
<!--                        :min="0"-->
<!--                        class="priceBox"-->
<!--                        @keyup.native="keyupEventBrokerage('brokerage', scope.$index, 2)"-->
<!--                      />-->
<!--                    </template>-->
<!--                  </el-table-column>-->
<!--                  <el-table-column align="center" label="二级返佣(%)" min-width="120">-->
<!--                    <template slot-scope="scope">-->
<!--                      <el-input-->
<!--                        maxlength="6"-->
<!--                        :disabled="isDisabled"-->
<!--                        v-model.trim="scope.row.brokerageTwo"-->
<!--                        type="number"-->
<!--                        :min="0"-->
<!--                        class="priceBox"-->
<!--                        @keyup.native="keyupEventBrokerage('brokerageTwo', scope.$index, 2)"-->
<!--                      />-->
<!--                    </template>-->
<!--                  </el-table-column>-->
<!--                </template>-->
<!--                <el-table-column-->
<!--                  v-for="(item, iii) in attrValue"-->
<!--                  :key="iii"-->
<!--                  :label="formThead[iii].title"-->
<!--                  align="center"-->
<!--                  min-width="120"-->
<!--                >-->
<!--                  <template slot-scope="scope">-->
<!--                    <el-input-->
<!--                      maxlength="6"-->
<!--                      :disabled="isDisabled"-->
<!--                      v-model.trim="scope.row[iii]"-->
<!--                      :type="formThead[iii].title === '商品编号' ? 'text' : 'number'"-->
<!--                      :min="0"-->
<!--                      type="number"-->
<!--                      class="priceBox"-->
<!--                      @keyup.native="keyupEvent(iii, scope.row[iii], scope.$index, 2)"-->
<!--                    />-->
<!--                  </template>-->
<!--                </el-table-column>-->
<!--              </el-table>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="全部sku：" v-if="$route.params.id && showAll">-->
<!--              <el-button type="default" @click="showAllSku()" :disabled="isDisabled">展示</el-button>-->
<!--            </el-form-item>-->
<!--            <el-form-item-->
<!--              v-if="formValidate.attr.length > 0 && formValidate.specType"-->
<!--              label="商品属性："-->
<!--              class="labeltop"-->
<!--              :class="isDisabled ? 'disLabel' : 'disLabelmoren'"-->
<!--            >-->
<!--              <el-table :data="ManyAttrValue" border class="tabNumWidth" size="mini">-->
<!--                <template v-if="manyTabDate">-->
<!--                  <el-table-column-->
<!--                    v-for="(item, iii) in manyTabDate"-->
<!--                    :key="iii"-->
<!--                    align="center"-->
<!--                    :label="manyTabTit[iii].title"-->
<!--                    min-width="80"-->
<!--                  >-->
<!--                    <template slot-scope="scope">-->
<!--                      <span class="priceBox" v-text="scope.row[iii]" />-->
<!--                    </template>-->
<!--                  </el-table-column>-->
<!--                </template>-->
<!--                <el-table-column align="center" label="图片" min-width="80">-->
<!--                  <template slot-scope="scope">-->
<!--                    <div class="upLoadPicBox" @click="modalPicTap('1', 'duo', scope.$index)">-->
<!--                      <div v-if="scope.row.image" class="pictrue tabPic"><img :src="scope.row.image" /></div>-->
<!--                      <div v-else class="upLoad tabPic">-->
<!--                        <i class="el-icon-camera cameraIconfont" />-->
<!--                      </div>-->
<!--                    </div>-->
<!--                  </template>-->
<!--                </el-table-column>-->
<!--                <el-table-column align="center" label="一级返佣(%)" min-width="120">-->
<!--                  <template slot-scope="scope">-->
<!--                    <el-input-->
<!--                      :disabled="isDisabled"-->
<!--                      v-model.trim="scope.row.brokerage"-->
<!--                      maxlength="6"-->
<!--                      type="number"-->
<!--                      :min="0"-->
<!--                      class="priceBox"-->
<!--                      @keyup.native="keyupEventBrokerage('brokerage', scope.$index, 3)"-->
<!--                    />-->
<!--                  </template>-->
<!--                </el-table-column>-->
<!--                <el-table-column align="center" label="二级返佣(%)" min-width="120">-->
<!--                  <template slot-scope="scope">-->
<!--                    <el-input-->
<!--                      maxlength="6"-->
<!--                      :disabled="isDisabled"-->
<!--                      v-model.trim="scope.row.brokerageTwo"-->
<!--                      type="number"-->
<!--                      :min="0"-->
<!--                      class="priceBox"-->
<!--                      @keyup.native="keyupEventBrokerage('brokerageTwo', scope.$index, 3)"-->
<!--                    />-->
<!--                  </template>-->
<!--                </el-table-column>-->
<!--                <el-table-column-->
<!--                  v-for="(item, iii) in attrValue"-->
<!--                  :key="iii"-->
<!--                  :label="formThead[iii].title"-->
<!--                  align="center"-->
<!--                  min-width="120"-->
<!--                >-->
<!--                  <template slot-scope="scope">-->
<!--                    <el-input-->
<!--                      :disabled="isDisabled"-->
<!--                      v-model.trim="scope.row[iii]"-->
<!--                      type="number"-->
<!--                      class="priceBox"-->
<!--                      @keyup.native="keyupEvent(iii, scope.row[iii], scope.$index, 3)"-->
<!--                    />-->
<!--                  </template>-->
<!--                </el-table-column>-->
<!--                <template v-if="formValidate.isSub"> </template>-->
<!--                <el-table-column v-if="!isDisabled" key="3" align="center" label="操作" min-width="80">-->
<!--                  <template slot-scope="scope">-->
<!--                    <el-button type="text" class="submission" @click="delAttrTable(scope.$index)">删除</el-button>-->
<!--                  </template>-->
<!--                </el-table-column>-->
<!--              </el-table>-->
<!--            </el-form-item>-->
<!--          </el-col>-->






















      </el-card>
      <br>
      <el-card id="tuwen" class="box-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>图文描述</span>
        </div>
        <el-form-item prop="mainImg" label="宝贝主图" :rules="[{ required: true, message: '请上传宝贝主图', trigger: 'blur' }]">
          <Upload v-model="postForm.mainImg" />
          <ImageSource style="margin-top: -5px;" :mul="false" v-model="postForm.mainImg" />
        </el-form-item>
        <el-form-item prop="goodsImg" label="宝贝相册" :rules="[{ required: true, message: '请上传宝贝相册', trigger: 'blur' }]">
          <MultipleUpload :value="postForm.goodsImg" v-model="postForm.goodsImg" />
          <ImageSource style="margin-top: 5px;" :mul="true" v-model="postForm.goodsImg" />
        </el-form-item>
        <el-form-item label="* 商品视频" prop="mainVideo" >
            <SingleVideoUpload v-model="postForm.mainVideo" />
        </el-form-item>
        <el-form-item prop="description" label="商品描述" :rules="[{ required: true, message: '必填', trigger: 'blur' }]">
          <el-input type="textarea" v-model="postForm.description" placeholder="" style="width: 60%;" />
        </el-form-item>
        <el-form-item prop="detail" label="商品详情" :rules="[{ required: true, message: '必填', trigger: 'blur' }]">
          <Tinymce ref="editor" v-model="postForm.detail" :height="400" style="width: 60%;"/>
        </el-form-item>
      </el-card>
      <br>
      <el-card id="zhifu" class="box-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>支付信息</span>
        </div>
        <el-form-item label="库存计算方式" prop="stockType" :rules="[{ required: true, message: '请选择', trigger: 'change' }]">
            <el-radio-group v-model="postForm.stockType" size="small">
              <el-radio :label="1" border>下单减库存</el-radio>
              <el-radio :label="2" border>付款减库存</el-radio>
            </el-radio-group>
        </el-form-item>
      </el-card>
      <br>
      <el-card id="wuliu" class="box-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>物流信息</span>
        </div>
        <el-form-item prop="freightTemplateId" label="运费模板" :rules="[{ required: true, message: '请选择', trigger: 'change' }]">
          <el-select v-model="postForm.freightTemplateId" filterable clearable placeholder="请选择" style="width: 60%;">
              <el-option
                v-for="item in freightOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <el-button @click="$router.push('/freight/list')"size="mini" type="danger">新建模板</el-button>
            <el-button @click="getFreightTemplate"size="mini" type="danger">刷新</el-button>
        </el-form-item>
      </el-card>
      <br>
      <el-card id="shouhou" class="box-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>售后信息</span>
        </div>
        <el-form-item label="上架状态" prop="status" :rules="[{ required: true, message: '请选择', trigger: 'change' }]">
            <el-radio-group v-model="postForm.status" size="small">
              <el-radio :label="1" border>出售中宝贝</el-radio>
              <el-radio :label="2" border>仓库中宝贝</el-radio>
            </el-radio-group>
        </el-form-item>
      </el-card>
      <br>
      <el-form-item>
        <el-button v-loading="loading" type="primary" @click="submitForm">
          保存
        </el-button>
      </el-form-item>
    </el-form>
    </div>
  </div>
</template>

<script>
  import Vue from 'vue'
  import MDinput from '@/components/MDinput'
  import {
    getShopCateList,
    getShopFreightList
  } from '@/api/shop'
  import {
    getGoodsCateList, getGoods, updateGoods, getThirdDetail,
    templateListApi,attrDeleteApi,attrCreatApi
  } from '@/api/goods'
  import {
    renderTime
  } from '@/utils'
  import Upload from '@/components/Upload/singleImage'
  import ImageSource from '@/components/Upload/imageSource'
  import MultipleUpload from '@/components/Upload/multipleImage'
  import Tinymce from '@/components/Tinymce'
  import SingleVideoUpload from '@/components/Upload/singleVideo'
  import SingleUpload from '@/components/Upload/singleUpload'
  import goodsDialog from '@/views/goods/publish/dialog/goods'

  const defaultForm = {
    type: 1,
    status: 1,
    stockType: 1,
  }

  const defaultObj = {
    image: '',
    sliderImages: [],
    sliderImage: '',
    name: '',
    intro: '',
    keyword: '',
    cateIds: [], // 商品分类id
    cateId: null, // 商品分类id传值
    unitName: '',
    sort: 0,
    isShow: false,
    tempId: '',
    attrValue: [
      {
        image: '',
        price: 0,
        cost: 0,
        otPrice: 0,
        stock: 0,
        barCode: '',
        weight: 0,
        volume: 0,
        brokerage: 0,
        brokerageTwo: 0,
      },
    ],
    attr: [],
    selectRule: '',
    isSub: false,
    content: '',
    specType: false,
    id: undefined,
    couponIds: [],
    coupons: [],
    categoryId: 0,
    guaranteeIds: '',
    guaranteeIdsList: [] || null,
    brandId: '',
  };

const objTitle = {
  price: {
    title: '售价（元）',
  },
  cost: {
    title: '成本价（元）',
  },
  otPrice: {
    title: '原价（元）',
  },
  stock: {
    title: '库存',
  },
  barCode: {
    title: '商品编号',
  },
  weight: {
    title: '重量（KG）',
  },
  volume: {
    title: '体积(m³)',
  },
  brokerage: {
    title: '一级返佣(%)',
  },
  brokerageTwo: {
    title: '二级返佣(%)',
  },
};

  export default {
    name: 'GoodsDetail',
    components: {
      MDinput,
      Upload,
      ImageSource,
      MultipleUpload,
      Tinymce,
      SingleVideoUpload,
      SingleUpload,
      goodsDialog
    },
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
             isBtn: false,
                manyTabTit: {},
                   manyTabDate: {},
        isDisabled: false,
        OneattrValue: [Object.assign({}, defaultObj.attrValue[0])], // 单规格
          ManyAttrValue: [Object.assign({}, defaultObj.attrValue[0])], // 多规格
          ruleList: [],
          merCateList: [], // 商户分类筛选
          shippingList: [], // 运费模板
          formThead: Object.assign({}, objTitle),
          formValidate: Object.assign({}, defaultObj),
          formDynamics: {
            ruleName: '',
            ruleValue: [],
          },
          tempData: {
            page: 1,
            limit: 9999,
          },
          manyTabTit: {},
          manyTabDate: {},
          grid2: {
            xl: 12,
            lg: 12,
            md: 12,
            sm: 24,
            xs: 24,
          },
          // 规格数据
          formDynamic: {
            attrsName: '',
            attrsVal: '',
          },
            attrInfo: {},
                  showAll: false,

        props:{ label: 'name', value : 'id', children: 'children'},
        postForm: Object.assign({}, defaultForm),
        loading: false,
        tempRoute: {},
        goodsCateOptions:[],
        shopCateOptions:[],
        freightOptions: [],
        activeName: 'jichu',
        groupList: [],
        singleGroup: {num: null, discounts: null},
        attrKey: '',
        attrKeyList: [],
        skuList:[],
        batchSet: false,
        temp: {},
        attrLength: 0,
        thirdGoodsUrl: '',
        autoGetLoading: false,
        showGoods: false,
      }
    },
      computed: {
        // visitedViews() {
        //   return this.$store.state.tagsView.visitedViews;
        // },

        // ...mapGetters(['adminProductClassify', 'merProductClassify', 'productBrand', 'shippingTemplates']),

        attrValue() {
          const obj = Object.assign({}, defaultObj.attrValue[0]);
          delete obj.image;
          delete obj.brokerage;
          delete obj.brokerageTwo;
          return obj;
        },
        oneFormBatch() {
          const obj = [Object.assign({}, defaultObj.attrValue[0])];
          delete obj[0].barCode;
          return obj;
        },
      },
    created() {
      this.init()
      if (this.isEdit) {
        const id = this.$route.params && this.$route.params.id
        this.getGoods(id)
      } else {
        this.postForm = Object.assign({}, defaultForm)
      }
      // Why need to make a copy of this.$route here?
      // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
      // https://github.com/PanJiaChen/vue-element-admin/issues/1221
      this.tempRoute = Object.assign({}, this.$route)


        this.tempRoute = Object.assign({}, this.$route);
          if (parseFloat(this.$route.params.id) > 0 && this.formValidate.specType) {
            this.$watch('formValidate.attr', this.watCh);
          }
          if (this.isCopy && checkPermi(['merchant:plat:product:brand:cache:list'])) this.getCopyConfig();

          if(!this.formValidate.specType){
            this.defaultAttr()
          }

    },
      watch: {
        'formValidate.attr': {
          handler: function (val) {
            //his.watCh(val); //重要！！！
            if (this.formValidate.specType && this.isAttr) this.watCh(val); //重要！！！
          },
          immediate: false,
          deep: true,
        },
      },
    methods: {
       //返佣输入
          keyupEventBrokerage(val, index, num) {
            switch (num) {
              case 1:
                this.oneFormBatch[index][val] = parseInt(this.oneFormBatch[index][val].replace(/\D|^0/g, ''));
                break;
              case 2:
                this.OneattrValue[index][val] = parseInt(this.OneattrValue[index][val].replace(/\D|^0/g, ''));
                break;
              default:
                this.ManyAttrValue[index][val] = parseInt(this.ManyAttrValue[index][val].replace(/\D|^0/g, ''));
            }
          },
          //价格输入
          keyupEvent(key, val, index, num) {
            var re = /^\D*([0-9]\d*\.?\d{0,2})?.*$/;
            console.log('val',val)
            switch (num) {
              case 1:
                this.oneFormBatch[index][key] =
                  key === 'stock' ? parseInt(val) : this.$set(this.oneFormBatch[index], key, val.replace(re, '$1'));
                break;
              case 2:
                this.OneattrValue[index][key] =
                  key === 'stock' ? parseInt(val) : this.$set(this.OneattrValue[index], key, val.replace(re, '$1'));
                break;
              default:
                this.ManyAttrValue[index][key] =
                  key === 'stock' ? parseInt(val) : this.$set(this.ManyAttrValue[index], key, val.replace(re, '$1'));
                break;
            }
          },
        watCh(val) {
            const tmp = {};
            const tmpTab = {};
            this.formValidate.attr.forEach((o, i) => {
              tmp[o.attrName] = { title: o.attrName };
              tmpTab[o.attrName] = '';
            });
            this.ManyAttrValue = this.attrFormat(val);
            console.log('    this.ManyAttrValue = ',    this.ManyAttrValue )
            if (this.formValidate.attrValue) {
              this.ManyAttrValue.forEach((val, index) => {
                const key = Object.values(val.attrValue).sort().join('/');
                if (this.attrInfo[key]) this.ManyAttrValue[index] = this.attrInfo[key];
              });
              this.attrInfo = [];
              this.ManyAttrValue.forEach((val) => {
                this.attrInfo[Object.values(val.attrValue).sort().join('/')] = val;
              });
            }

            this.manyTabTit = tmp;
            this.manyTabDate = tmpTab;
            this.formThead = Object.assign({}, this.formThead, tmp);
          },
          attrFormat(arr) {
            let data = [];
            const res = [];
            return format(arr);
            function format(arr) {
              if (arr.length > 1) {
                arr.forEach((v, i) => {
                  if (i === 0) data = arr[i]['attrValue'];
                  const tmp = [];
                  if (!data) return;
                  data.forEach(function (vv) {
                    arr[i + 1] &&
                      arr[i + 1]['attrValue'] &&
                      arr[i + 1]['attrValue'].forEach((g) => {
                        const rep2 = (i !== 0 ? '' : arr[i]['attrName'] + '_') + vv + '$&' + arr[i + 1]['attrName'] + '_' + g;
                        tmp.push(rep2);
                        if (i === arr.length - 2) {
                          const rep4 = {
                            image: '',
                            price: 0,
                            cost: 0,
                            otPrice: 0,
                            barCode: '',
                            stock: 0,
                            weight: 0,
                            volume: 0,
                            brokerage: 0,
                            brokerageTwo: 0,
                          };
                          rep2.split('$&').forEach((h, k) => {
                            const rep3 = h.split('_');
                            if (!rep4['attrValue']) rep4['attrValue'] = {};
                            rep4['attrValue'][rep3[0]] = rep3.length > 1 ? rep3[1] : '';
                          });
                          for (let attrValueKey in rep4.attrValue) {
                            rep4[attrValueKey] = rep4.attrValue[attrValueKey];
                          }
                          res.push(rep4);
                        }
                      });
                  });
                  data = tmp.length ? tmp : [];
                });
              } else {
                const dataArr = [];
                arr.forEach((v, k) => {
                  v['attrValue'].forEach((vv, kk) => {
                    dataArr[kk] = v['attrName'] + '_' + vv;
                    res[kk] = {
                      image: '',
                      price: 0,
                      cost: 0,
                      otPrice: 0,
                      stock: 0,
                      barCode: '',
                      weight: 0,
                      volume: 0,
                      brokerage: 0,
                      brokerageTwo: 0,
                      attrValue: { [v['attrName']]: vv },
                    };
                    for (let attrValueKey in res[kk].attrValue) {
                      res[kk][attrValueKey] = res[kk].attrValue[attrValueKey];
                    }
                  });
                });
                data.push(dataArr.join('$&'));
              }
              return res;
            }
          },
       // 添加规则；
          addRule() {
            const _this = this;
            this.$modalAttr(this.formDynamics, function () {
              _this.productGetRule();
            });
          },
          // 选择规格
          onChangeSpec(num) {
            this.isAttr = true;
            if (num) this.productGetRule();
          },
          // 选择属性确认
          confirm() {
            this.isAttr = true;
            if (!this.formValidate.selectRule) {
              return this.$message.warning('请选择属性');
            }
            const data = [];
            this.ruleList.forEach((item) => {
              if (item.id === this.formValidate.selectRule) {
                item.ruleValue.forEach((i) => {
                  data.push({
                    attrName: i.value,
                    attrValue: i.detail,
                  });
                });
              }
              this.formValidate.attr = data;
            });
          },
          // 获取商品属性模板；
          productGetRule() {
            templateListApi(this.tableFrom).then((res) => {


              const list = res.data.list;

              console.log(list)
              for (var i = 0; i < list.length; i++) {
                list[i].ruleValue = JSON.parse(list[i].ruleValue);
              }
              this.ruleList = list;
            });
          },
          showInput(item) {
            this.$set(item, 'inputVisible', true);
          },
          onChangetype(item) {
            // if (item === 1) {
            //   this.OneattrValue.map((item) => {
            //     this.$set(item, 'brokerage', 0);
            //     this.$set(item, 'brokerageTwo', 0);
            //   });
            //   this.ManyAttrValue.map((item) => {
            //     this.$set(item, 'brokerage', 0);
            //     this.$set(item, 'brokerageTwo', 0);
            //   });
            // } else {
            //   this.OneattrValue.map((item) => {
            //     // delete item.brokerage;
            //     // delete item.brokerageTwo;
            //     this.$set(item, 'brokerage', 0);
            //     this.$set(item, 'brokerageTwo', 0);
            //   });
            //   this.ManyAttrValue.map((item) => {
            //     this.$set(item, 'brokerage', 0);
            //     this.$set(item, 'brokerageTwo', 0);
            //     // delete item.brokerage;
            //     // delete item.brokerageTwo;
            //   });
            // }
          },
          // 删除表格中的属性
          delAttrTable(index) {
            this.ManyAttrValue.splice(index, 1);
          },
          // 批量添加
          batchAdd() {
            // if (!this.oneFormBatch[0].pic || !this.oneFormBatch[0].price || !this.oneFormBatch[0].cost || !this.oneFormBatch[0].ot_price ||
            //     !this.oneFormBatch[0].stock || !this.oneFormBatch[0].bar_code) return this.$Message.warning('请填写完整的批量设置内容！');
            for (const val of this.ManyAttrValue) {
              this.$set(val, 'image', this.oneFormBatch[0].image);
              this.$set(val, 'price', this.oneFormBatch[0].price);
              this.$set(val, 'cost', this.oneFormBatch[0].cost);
              this.$set(val, 'otPrice', this.oneFormBatch[0].otPrice);
              this.$set(val, 'barCode', this.oneFormBatch[0].barCode);
              this.$set(val, 'stock', this.oneFormBatch[0].stock);
              this.$set(val, 'weight', this.oneFormBatch[0].weight);
              this.$set(val, 'volume', this.oneFormBatch[0].volume);
              this.$set(val, 'brokerage', this.oneFormBatch[0].brokerage);
              this.$set(val, 'brokerageTwo', this.oneFormBatch[0].brokerageTwo);
            }
          },
          // 添加按钮
          addBtn() {
            this.clearAttr();
            this.isBtn = true;
          },
          // 取消
          offAttrName() {
            this.isBtn = false;
          },
          clearAttr() {
            this.isAttr = true;
            this.formDynamic.attrsName = '';
            this.formDynamic.attrsVal = '';
          },
          // 删除规格
          handleRemoveAttr(index) {
            this.isAttr = true;
            this.formValidate.attr.splice(index, 1);
            this.manyFormValidate.splice(index, 1);
          },
          // 删除属性
          handleClose(item, index) {
            item.splice(index, 1);
          },
          // 添加规则名称
          createAttrName() {
            this.isAttr = true;
            if (this.formDynamic.attrsName && this.formDynamic.attrsVal) {
              const data = {
                attrName: this.formDynamic.attrsName,
                attrValue: [this.formDynamic.attrsVal],
              };
              this.formValidate.attr.push(data);
              var hash = {};
              this.formValidate.attr = this.formValidate.attr.reduce(function (item, next) {
                /* eslint-disable */
                hash[next.attrName] ? '' : (hash[next.attrName] = true && item.push(next));
                return item;
              }, []);
              this.clearAttr();
              this.isBtn = false;
            } else {
              this.$Message.warning('请添加完整的规格！');
            }
          },
          // 添加属性
          createAttr(num, idx) {
            this.isAttr = true;
            if (num) {
              this.formValidate.attr[idx].attrValue.push(num);
              var hash = {};
              this.formValidate.attr[idx].attrValue = this.formValidate.attr[idx].attrValue.reduce(function (item, next) {
                /* eslint-disable */
                hash[next] ? '' : (hash[next] = true && item.push(next));
                return item;
              }, []);
              this.formValidate.attr[idx].inputVisible = false;
            } else {
              this.$message.warning('请添加属性');
            }
          },
          //点击展示所有多规格属性
          showAllSku() {
            if (this.isAttr == false) {
              this.isAttr = true;
              if (this.formValidate.specType && this.isAttr) this.watCh(this.formValidate.attr); //重要！！！
            } else if (this.isAttr == true) {
              this.isAttr = false;
              this.getInfo();
            }
          },


      scrollTo(id) {
         let targetbox = document.getElementById(id);
        let top = targetbox.offsetTop-100;
        document.getElementById('wrap-form').scrollTop = top;
      },
      init(){
        this.getShopCateList();
        this.getFreightTemplate();
        getGoodsCateList().then(response => {
          this.goodsCateOptions = response.data
        }).catch(err => {
          console.log(err)
        })
        this.groupList.push({num: null, discounts: null})
      },
      getShopCateList(){
        getShopCateList().then(response => {
          this.shopCateOptions = response.data
        }).catch(err => {
          console.log(err)
        })
      },
      getFreightTemplate(){
        getShopFreightList().then(response => {
          this.freightOptions = response.data.list
        }).catch(err => {
          console.log(err)
        })
      },
      getGoods(id) {
        getGoods({
          goodsId: id
        }).then(response => {
          let goods = response.data.goods
          this.groupList = response.data.goodsGroupList
          if(goods.type == 2){
            goods.seckillDateRange = [goods.seckillBeginTime, goods.seckillEndTime]
          }
          if(goods.cateIds){
            goods.goodsCateId = goods.cateIds.split(",").map(i => parseInt(i, 0))
          }
          if(goods.shopCateIds){
            goods.shopCateId = goods.shopCateIds.split(",").map(i => parseInt(i, 0))
          }
          this.postForm = goods;
          this.attrKeyList = JSON.parse(response.data.attrKeyList);
          this.attrKeyList.forEach(item =>{
            item.attrValueList = JSON.parse(item.attrValueList);
          })
          this.skuList = JSON.parse(response.data.skuList);
          this.attrLength = this.attrKeyList.length

          if( this.skuList .length>1){
              this.formValidate.specType =true
          }


        }).catch(err => {
          console.log(err)
        })
      },
      submitForm() {
        this.$refs.postForm.validate(valid => {
          if (valid) {



              this.loading = true
              let formData = Object.assign({}, this.postForm)
              formData.addTime = null
              formData.updTime = null
              if (formData.type == 3 && this.groupList && this.groupList.length > 0) {
                formData.groupJson = JSON.stringify(this.groupList);
              }
              if(formData.seckillDateRange){
                formData.seckillBeginTime = renderTime(formData.seckillDateRange[0])
                formData.seckillEndTime = renderTime(formData.seckillDateRange[1])
              }
              if(formData.goodsCateId){
                formData.goodsCateIds = formData.goodsCateId.join(",")
                formData.goodsCateId = null
              }
              formData.shopCateIds = formData.shopCateId
              if(formData.shopCateId && formData.shopCateId.length > 0){
                formData.shopCateIds = formData.shopCateId.join(",")
                formData.shopCateId = null
              }
            //添加SKU
            //['黑', '大', '22', '33', '111', '1', '12', __ob__: Observer]
            /* console.log(this.skuList);
            let attrLength = this.attrLength;
            let tempList = Object.assign([], this.skuIdList);
            this.skuList.forEach(function(item, index){
              let temp = tempList[index];
              temp = [].concat(temp).concat(item[attrLength] ? item[attrLength] : 'NULL');
              temp = [].concat(temp).concat(item[attrLength+1] ? item[attrLength+1] : 'NULL');
              temp = [].concat(temp).concat(item[attrLength+2] ? item[attrLength+2] : 'NULL');
              temp = [].concat(temp).concat(item[attrLength+3] ? item[attrLength+3] : 'NULL');
              temp = [].concat(temp).concat(item[attrLength+4] ? item[attrLength+4] : 'NULL');
              Vue.set(tempList, index, temp);
            })
            let skuId = tempList;
            console.log(this.skuIdList); */
            console.log('formData',formData);
            this.loading = true
            formData.attrKeyList = JSON.stringify(this.attrKeyList)
            formData.skuList = JSON.stringify(this.skuList)

            // console.log('this.formValidate.attr',this.formValidate.attr);
            // console.log('this.formValidate.attrValue',this.formValidate.attrValue);

            // if (this.formValidate.specType && this.formValidate.attr.length < 1) return this.$message.warning('请填写多规格属性！');
            // if (this.formValidate.specType) {
            //       this.formValidate.attrValue = this.ManyAttrValue;
            //       this.formValidate.attr = this.formValidate.attr.map((item) => {
            //         console.log( item.attrValue)
            //         return {
            //           attrName: item.attrName,
            //           id: item.id,
            //           attrValue: item.attrValue,
            //           attrValues: item.attrValue.join(','),
            //         };
            //       });
            //       for (var i = 0; i < this.formValidate.attrValue.length; i++) {
            //         this.$set(this.formValidate.attrValue[i], 'id', 0);
            //         this.$set(this.formValidate.attrValue[i], 'productId', 0);
            //         this.$set(
            //           this.formValidate.attrValue[i],
            //           'attrValue',
            //           JSON.stringify(this.formValidate.attrValue[i].attrValue),
            //         ); //
            //         delete this.formValidate.attrValue[i].value0;
            //       }
            //     } else {
            //       this.formValidate.attr = [
            //         {
            //           attrName: '规格',
            //           attrValue: '默认',
            //           id: parseFloat(this.$route.params.id) > 0 ? this.formValidate.attr[0].id : 0,
            //         },
            //       ];
            //       this.OneattrValue.map((item) => {
            //         this.$set(item, 'attrValue', JSON.stringify({ 规格: '默认' }));
            //         this.$set(item, 'productId', 0);
            //       });
            //       this.formValidate.attrValue = this.OneattrValue;
            //     }



            // formData.attrKeyList = JSON.stringify(this.formValidate.attr)
            //  formData.skuList = JSON.stringify(this.formValidate.attrValue)





            updateGoods(formData).then((response) => {
              this.postForm.id = response.data
              this.$notify({
                title: '成功',
                message: '保存成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              // 调用全局挂载的方法
              this.$store.dispatch('tagsView/delView', this.$route)
              // 返回上一步路由
              this.$router.push('/goods/list')
            }).catch(err => {
              this.loading = false
              console.log(err)
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      addGroup(){
        this.groupList.push({num: null, discounts: null})
      },
      deleteGroup(index){
        this.groupList.splice(index,1)
      },
      handleClickTab(tab, event) {
      	this.activeName = tab.name
        this.scrollTo(this.activeName);
      },

        // 选择规格
        onChangeSpecnew(num) {
            console.log(num)
          this.isAttr = true;
          if (num) {
              this.manyAttr();
          }else{
            this.defaultAttr() ;
          }
          // <el-button type="default" class="button-new-tag" size="mini" @click="defaultAttr" icon="el-icon">统一规格</el-button>
          // <el-button type="default" class="button-new-tag" size="mini" @click="manyAttr" icon="el-icon">多规格</el-button>

        },



    defaultAttr(){
        this.attrKeyList =
          [{
            attrKey:"默认",
            attrValueList:['统一规格'],
          }]
        this.createSkuList()
      },
      manyAttr(){
        this.attrKeyList=  [];
      },
      addAttrKey(){
        if(!this.attrKey){
          this.$message.error('产品属性不能为空');
        }
        this.attrKey.split(" ").forEach((item)=>{
          if(item != '') {
            this.attrKeyList.push({attrKey:item});
          }
        })
        this.attrKey = '';
      },
      addAttrValue(item){
        if(!item.attrValue){
          this.$message.error('产品属性不能为空');
        }
        if(!item.attrValueList){
          item.attrValueList = []
        }
        item.attrValue.split(" ").forEach((result)=>{
          if(result != '') {
            item.attrValueList.push(result);
          }
        })
        item.attrValue = '';
        this.createSkuList()
      },
      handleCloseKey(index) {
        this.attrKeyList.splice(index, 1);
        this.createSkuList()
      },
      handleCloseValue(item, value,index) {
        item.attrValueList.splice(item.attrValueList.indexOf(value), 1);
        this.$set(this.attrKeyList, index, item);
        this.createSkuList()
      },
      createSkuList(){
      	let list = [];
      	this.attrKeyList.forEach(function(item){
      		let attrVal = [];
          if(item.attrValueList){
            item.attrValueList.forEach(function(val){
              attrVal.push(val);
            })
          }
      		if(attrVal && attrVal.length > 0){
      			list.push(attrVal)
      		}
      	})
        console.log("list", list);
      	if(list.length > 1 || list.length == this.attrKeyList.length){
      		this.skuList = this.descartes(list);
      		let tempList = this.skuList;
      		tempList.forEach(function(item, index){
      			if(!Array.isArray(item)){
      				item = [].concat(item);
      				Vue.set(tempList, index, item)
      			}
            item.push('')
            item.push('')
            item.push('')
            item.push('')
            item.push('')
            item.push('')
      		})
      		this.skuList = tempList;
      		this.attrLength = this.attrKeyList.length
          console.log("attrLength", this.attrLength);
      	}
      	console.log("skuList", this.skuList)
      },
      descartes(array){
      	if( array.length < 2 )
      		return array[0] || [];
      	return [].reduce.call(array, function(col, set) {
      		var res = [];
      		col.forEach(function(c) {
      			set.forEach(function(s) {
      				var t = [].concat( Array.isArray(c) ? c : [c] );
      				t.push(s);
      				res.push(t);
      				})
      			});
      		return res;
      		});
      	},
      batchSetParams(val, index){
        this.skuList.forEach(item=>{
          Vue.set(item, index, val);
        })
        // this.$set(this.skuList, index, val);
      },
      selectChange(val){
        this.$forceUpdate();
      },
      getThirdDetail(){
        this.autoGetLoading = true;
        getThirdDetail({url:this.thirdGoodsUrl}).then(response => {
          let goodsResult = response.data
          console.log(goodsResult)
          this.postForm = goodsResult;
          this.postForm.status = 1;
          this.postForm.stockType =1;
          this.attrKeyList = JSON.parse(this.postForm.attrKeyList);
          this.attrKeyList.forEach(item =>{
            item.attrValueList = JSON.parse(item.attrValueList);
          })
          if(this.postForm.skuList){
            this.skuList = JSON.parse(this.postForm.skuList);
          }
          this.attrLength = this.attrKeyList.length
          this.autoGetLoading = false;
        }).catch(err => {
          console.log(err)
          this.autoGetLoading = false;
        })
      },
      openGoodsDialog(){
        this.showGoods = true
      },
      closeGoodsDialog(){
        this.showGoods = false
      },
      // 回调选择的商品
      selectedGoods(goodsId) {
        if(!goodsId){
          return;
        }

        getGoods({
          goodsId: goodsId
        }).then(response => {

          let goods = response.data.goods
          if(goods.cateIds){
            goods.goodsCateId = goods.cateIds.split(",").map(i => parseInt(i, 0))
          }
          this.postForm = goods;
          this.postForm.id = null
          this.attrKeyList = JSON.parse(response.data.attrKeyList);
          this.attrKeyList.forEach(item =>{
            item.attrValueList = JSON.parse(item.attrValueList);
          })
          let skuList = JSON.parse(response.data.skuList);
          // skuList.forEach((item, index)=>{
          //   item[1]=null;
          //   item[2]=null;
          //   item[3]=null;
          // })

          this.skuList = skuList;
          this.attrLength = this.attrKeyList.length
          this.allUnits = response.data.goodsUnitConvertList


        }).catch(err => {
          console.log(err)
        })
      },

    }
  }
</script>

<style lang="scss" scoped>
  .el-radio {
    margin-right: 0px !important;
  }

  ::v-deep .el-card__header {
    color: #333333;
    background-color: #f5f5f5;
    border-color: #ddd;
  }
  .sku-item {
    position: relative;
  }
  .sku-item i {
    display: none;
    position: absolute;
    top: 0;
    right: 0;
    transform: translateX(50%) translateY(-50%);
  }
  .sku-item::hover {
    display: block;
  }



  .input-new-tag{
      width: 90px;
      margin-left: 10px;
      vertical-align: bottom;
  }

 .mb5{
   margin-bottom:5px;
 }
 .mr10{
     margin-right:10px
 }


</style>
